const TencentCloudCommon = require("tencentcloud-sdk-nodejs-common");
const CommonClient = TencentCloudCommon.CommonClient;
function generateSessionId() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16 | 0,
          v = c == 'x'? r : (r & 0x3 | 0x8);
      return v.toString(16);
  });
}
class TencentTTS {
  /**
   * 初始化TTS客户端
   * @param {string} secretId - 腾讯云SecretId
   * @param {string} secretKey - 腾讯云SecretKey
   * @param {string} [region='ap-beijing'] - 区域代码
   */
  constructor(secretId='AKID2uZ3KNC3g5FBsLZYKsBGWYKrAF6i6E8n', secretKey='UAfw0pRwEI8kHbmjSx64qRq55sQnz50l', region = 'ap-beijing') {
    if (!secretId || !secretKey) {
      throw new Error('Missing required credentials: secretId and secretKey');
    }
    const clientConfig = {
      credential: {
        secretId: secretId,
        secretKey: secretKey,
      },
      region: "ap-nanjing",
      profile: {
        httpProfile: {
          endpoint: "tts.tencentcloudapi.com",
        },
      },
    };
    this.client = new CommonClient(
      "tts.tencentcloudapi.com", // 服务产品名
      '2019-08-23', // API版本
      clientConfig
    );
  }

  /**
   * 文本转语音
   * @param {string} text - 需要合成的文本（UTF-8编码，最大300字）
   * @param {Object} [options={}] - 附加参数
   * @param {string} [options.SessionId] - 会话ID（可用于跟踪请求）
   * @param {number} [options.ModelType=1] - 模型类型（1：默认，2：轻量版）
   * @param {number} [options.VoiceType=0] - 音色选择
   * @param {number} [options.Speed=0] - 语速（-2到2，默认0）
   * @returns {Promise<Object>} - 返回合成结果
   */
  async synthesize(text, options = { }) {
    options.SessionId=generateSessionId();
    if (!text || typeof text !== 'string') {
      throw new Error('Invalid text parameter');
    }

    const params = {
      Text: text,
      Codec: "mp3",
      ...options
    };

    try {
      return await this.client.request('TextToVoice', params);
    } catch (error) {
      console.error('TTS request failed:', error);
      throw new Error(`TTS synthesis failed: ${error.message}`);
    }
  }
}

module.exports = TencentTTS;